package com.example.myapplication.databinding;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.myapplication.databinding.bean.vegetable.ObservableVegetable;
import com.example.myapplication.databinding.bean.vegetable.Vegetable;
import com.example.myapplication.databinding.bean.vegetable.VegetableViewModel;
import com.example.myapplication.databinding.viewmodel.UserViewModel;

/**
 * Created by xiaolong on 2022/1/2 9:39 下午
 * email：xinxiaolong123@foxmail.com
 */
public class DataBindingActivity extends AppCompatActivity {

    ActivityDatabindingLayoutBinding binding;


    private VegetableViewModel vegetableViewModel = new VegetableViewModel();
    private Vegetable vegetable = new Vegetable();
    private ObservableVegetable obVegetable = new ObservableVegetable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDatabindingLayoutBinding.inflate(getLayoutInflater());

        UserViewModel userViewModel=new ViewModelProvider(this).get(UserViewModel.class);

        binding.setLifecycleOwner(this);
        setContentView(binding.getRoot());
        initData();
        initEvent();
    }

    private void initData() {
        vegetable.setName("土豆");
        vegetable.setColor("黄色");
        vegetable.setPrice(2.5);
        vegetableViewModel.getVegetable().setValue(vegetable);
        binding.setMuVegetavle(vegetableViewModel);

        obVegetable.setName("土豆");
        obVegetable.setColor("黄色");
        obVegetable.setPrice(2.5);
        binding.setObVegetavle(obVegetable);
    }

    private void initEvent() {

        binding.btnMuAddPrice.setOnClickListener(v -> {

            vegetable.setPrice(vegetable.getPrice() + 1);

            vegetableViewModel.getVegetable().setValue(vegetable);

        });


        binding.btnObAddPrice.setOnClickListener(v -> {
            obVegetable.setPrice(obVegetable.getPrice() + 1);

        });


        boolean has = vegetableViewModel.getVegetable().hasObservers();

        vegetableViewModel.getVegetable().observe(this, new Observer<Vegetable>() {
            @Override
            public void onChanged(Vegetable vegetable) {
                String name = vegetable.getName();
            }
        });

        has = vegetableViewModel.getVegetable().hasObservers();

        vegetableViewModel.getVegetable().observe(this, new Observer<Vegetable>() {
            @Override
            public void onChanged(Vegetable vegetable) {

            }
        });

    }
}
